package org.mspring.platform.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用于处理classpath下的资源文件
 *
 * @since 2014-03-21 16:09:37
 * @author Gao Youbo
 */
public class ClassPathResourceUtils {

    private static final Logger log = LoggerFactory.getLogger(ClassPathResourceUtils.class);

    private static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 加载资源
     *
     * @param resourceName
     * @return
     */
    public static String readResource(String resourceName) {
        return readResource(resourceName, DEFAULT_CHARSET);
    }

    /**
     * 加载资源
     *
     * @param resourceName
     * @param charset
     * @return
     */
    public static String readResource(String resourceName, String charset) {
        StringBuilder sb = new StringBuilder();
        List<String> lines = readResourceAsList(resourceName, charset);
        for (String line : lines) {
            sb.append(line);
        }
        return sb.toString();
    }

    /**
     * 加载资源
     *
     * @param resourceName
     * @return
     */
    public static List<String> readResourceAsList(String resourceName) {
        return readResourceAsList(resourceName, DEFAULT_CHARSET);
    }

    public static List<String> readResourceAsList(String resourceName, String charset) {
        try {
            return IOUtils.readLines(getResourceAsStream(resourceName), charset);
        } catch (IOException ex) {
            log.error("加载资源失败", ex);
            return new ArrayList<>();
        }
    }

    public static void writeResource(String resourceName, String value) {
        writeResource(resourceName, value, DEFAULT_CHARSET);
    }

    /**
     * 写入文件
     *
     * @param resourceName
     * @param value
     * @param charset
     */
    public static void writeResource(String resourceName, String value, String charset) {
        try {
            FileUtils.write(getResource(resourceName), value, charset);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    public static File getResource(String resourceName) {
        URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
        return FileUtils.toFile(url);
    }

    public static InputStream getResourceAsStream(String resourceName) {
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName);
    }

}
